#include "httpServer.hpp"
#include <memory>
// tcpServer  serverport
static void Usage(char *s)
{
    cout << "\nUsage:\n\t" << s << " serverport" << endl;
}

string suffixtoDest(const string& suffix)
{
    string ct = "Content-Type: ";
    if(suffix == ".html")
        ct += "text/html";
    else if(suffix == ".jpg")
        ct += "application/x-jpg";
    else if(suffix == ".mp4")
        ct += "	video/mpeg4";
    ct += "\r\n";
    return ct;
}

bool Get(const httpRequest& req,httpResponse& resp)
{
    cout<<"--------------- http start -----------------"<<endl;
    cout<<req.inbuffer<<endl;
    cout<<req.method<<endl;
    cout<<req.url<<endl;
    cout<<req.httpversion<<endl;
    cout<<req.path<<endl;
    cout<<req.suffix<<endl;
    cout<<req.size<<endl;
    cout<<"--------------- http end   -----------------"<<endl;

    //手动添加到resp中outbuffer中，我们这里只做测试
    string respline = "HTTP/1.1 200 OK\r\n";
    string respheader = suffixtoDest(req.suffix);
    //string respheader = "Content-Type: text/html\r\n";
    string respblack = "\r\n";
    string body;
    body.resize(req.size+1);  //这里保证多一个字符，保证语言上的安全
    //string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>北京交通广播《一路畅通》“交通大家谈”节目，特邀北京市交通委员会地面公交运营管理处处长赵震、北京市公安局公安交通管理局秩序处副处长 林志勇、北京交通发展研究院交通规划所所长 刘雪杰为您解答公交车专用道6月1日起社会车辆进出公交车道须注意哪些？</p></body></html>";
    if(!Util::readFile(req.path,(char*)body.c_str(),req.size))
    {
        Util::readFile(html_404,(char*)body.c_str(),req.size);
        // cout<<"################404"<<endl;
        // cout<<html_404<<endl;
    }
    //添加报文
    respheader += "Content-Length: ";
    respheader += to_string(body.size());
    respheader += "\r\n";
    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblack;
    //打印出来，让我们看看验证结果
    cout<<"---------------------response start------------------"<<endl;
    cout<<resp.outbuffer<<endl;
    cout<<"---------------------response  end ------------------"<<endl;

    resp.outbuffer += body;
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        // 使用手册
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<httpserver> ts(new httpserver(Get,port));
    ts->initServer();
    ts->start();
    return 0;
}